package com.antdesignbackend.backend.task;

import com.antdesignbackend.backend.animalNumber.entity.AnimalNumber;
import com.antdesignbackend.backend.animalNumber.service.AnimalNumberService;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.MonthReportRecord;
import com.antdesignbackend.backend.entity.Production;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.antdesignbackend.backend.service.MonthReportRecordService;
import com.antdesignbackend.backend.service.ProductionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时器计划任务等
 */

@Slf4j
@Component
public class ScheduledTask {

//    private boolean isf = false;

    private AnimalNumberService animalNumberService;
    private  MonthReportRecordService monthReportRecordService;
    private EnterpriseService enterpriseService;
    private ProductionService productionService;
    @Autowired
    public ScheduledTask(AnimalNumberService animalNumberService,MonthReportRecordService monthReportRecordService,EnterpriseService enterpriseService,ProductionService productionService) {
        this.animalNumberService = animalNumberService;
        this.monthReportRecordService=monthReportRecordService;
        this.enterpriseService=enterpriseService;
        this.productionService=productionService;
    }
    /**
     * 每天凌晨执行一次
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void LogicTask() {
        try {
            //拿到哺乳需要转保育的家畜
            QueryWrapper<AnimalNumber> wrapper = new QueryWrapper<>();
            wrapper.eq("AnimalType",1) //牲畜
                    .le("ConservationTime",new Date()); //哺乳转保育的时间小于等于当前时间
            List<AnimalNumber> list = animalNumberService.list(wrapper);
            if (!list.isEmpty()){
                for (AnimalNumber animalNumber:list){
                    animalNumber.setConservation(animalNumber.getConservation() + animalNumber.getLactation());
                    animalNumber.setLactation(0);
                }
                animalNumberService.updateBatchById(list);
            }
            QueryWrapper<AnimalNumber> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("AnimalType",1) //牲畜
                    .le("GrowTime",new Date()); //保育转育成时间小于等于当前时间
            List<AnimalNumber> list1 = animalNumberService.list(wrapper1);
            if (!list1.isEmpty()){
                for (AnimalNumber animalNumber:list1){
                    animalNumber.setCommodity(animalNumber.getCommodity() + animalNumber.getConservation());
                    animalNumber.setConservation(0);
                }
                animalNumberService.updateBatchById(list1);
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    /**
     * 每月的凌晨一点生成月报表记录
     */
//    @Scheduled(fixedRate = 1000)
    @Scheduled(cron = "0 0 1 1 * ?")
    public void reportTask() {
//        if (isf) return;
//        isf = true;
        try {
            MonthReportRecord monthReportRecord=new MonthReportRecord();
            QueryWrapper<Enterprise> enterpriseQueryWrapper=new QueryWrapper<>();
            enterpriseQueryWrapper.eq("examine",1).eq("animalTypes",1);
            List<Enterprise> enterprises=enterpriseService.list(enterpriseQueryWrapper);
            for(Enterprise enterprise:enterprises){
                List<String> strings=getDay(new Date());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date firstDay=sdf.parse(strings.get(0));        //上个月第一天的日期
                Date lastDay=sdf.parse(strings.get(1));         //上个月最后一天的日期
                QueryWrapper<AnimalNumber> animalNumberQueryWrapper=new QueryWrapper<>();
                animalNumberQueryWrapper.eq("eid",enterprise.getEnterpriseId());
                List<AnimalNumber> animalNumbers=animalNumberService.list(animalNumberQueryWrapper);
                int maleSum = 0,femaleSum=0,breedFemaleSum=0,lactationSum=0,conservationSum=0,growSum=0;
                for(AnimalNumber animalNumber:animalNumbers){
                    maleSum=maleSum+animalNumber.getSpecies();
                    femaleSum=femaleSum+animalNumber.getReserve();
                    breedFemaleSum=breedFemaleSum+animalNumber.getMenstruation();
                    lactationSum=lactationSum+animalNumber.getLactation();
                    conservationSum=conservationSum+animalNumber.getConservation();
                    growSum=growSum+animalNumber.getCommodity();
                }
                monthReportRecord.setEid(enterprise.getEnterpriseId());       //设置eid
                monthReportRecord.setReportMonth(firstDay);             //设置上报月份
                monthReportRecord.setMaleLivestock(maleSum);            //设置种公畜存栏数
                monthReportRecord.setFemaleLivestock(femaleSum);        //设置后备母畜存栏数
                monthReportRecord.setBreedFemaleLivestock(breedFemaleSum);          //设置能繁母畜存栏数
                monthReportRecord.setLactationLivestock(lactationSum);              //设置哺乳牲畜存栏数
                monthReportRecord.setConservationLivestock(conservationSum);        //设置保育牲畜存栏数
                monthReportRecord.setGrowLivestock(growSum);                        //设置育成牲畜存栏数
                monthReportRecord.setLivestockSum(maleSum+femaleSum+breedFemaleSum+lactationSum+conservationSum+growSum);       //设置存栏数合计
                QueryWrapper<Production> productionQueryWrapper=new QueryWrapper<>();
                productionQueryWrapper.eq("eid",enterprise.getEnterpriseId()).eq("situation","出生").between("changeTime",firstDay,lastDay);
                monthReportRecord.setFetusNumber(productionService.count(productionQueryWrapper));      //设置产仔胎数
                List<Production> productions=productionService.list(productionQueryWrapper);
                int litterNumberSum=0;
                for(Production production:productions){
                    litterNumberSum=litterNumberSum+production.getLactation();
                }
                monthReportRecord.setLitterNumber(litterNumberSum);                //设置产仔数
                QueryWrapper<Production> productionQueryWrapper1=new QueryWrapper<>();
                productionQueryWrapper1.eq("eid",enterprise.getEnterpriseId()).eq("situation","调出").between("changeTime",firstDay,lastDay);
                List<Production> productions1=productionService.list(productionQueryWrapper1);
                int malePublicationSum=0,femalePublicationSum=0,breedFemalePublicationSum=0,lactationPublicationSum=0,conservationPublicationSum=0,growPublicationSum=0;
                for(Production production:productions1){
                    malePublicationSum=malePublicationSum+production.getMale();
                    femalePublicationSum=femalePublicationSum+production.getFemale();
                    breedFemalePublicationSum=breedFemalePublicationSum+production.getBreedFemale();
                    lactationPublicationSum=lactationPublicationSum+production.getLactation();
                    conservationPublicationSum=conservationPublicationSum+production.getConservation();
                    growPublicationSum=growPublicationSum+production.getGrow();
                }
                monthReportRecord.setMalePublication(malePublicationSum);       //设置种公畜出栏数
                monthReportRecord.setFemalePublication(femalePublicationSum);       //设置后备母畜禽出栏数
                monthReportRecord.setBreedFemalePublication(breedFemalePublicationSum);     //设置能繁母畜禽出栏数
                monthReportRecord.setLactationPublication(lactationPublicationSum);         //设置哺乳牲畜出栏数
                monthReportRecord.setConservationPublication(conservationPublicationSum);       //设置保育牲畜出栏数
                monthReportRecord.setGrowPublication(growPublicationSum);           //设置育成牲畜出栏数
                monthReportRecord.setPublicationSum(malePublicationSum+femalePublicationSum+breedFemalePublicationSum+lactationPublicationSum+conservationPublicationSum+growPublicationSum);       //设置出栏数合计
                QueryWrapper<Production> productionQueryWrapper2=new QueryWrapper<>();
                productionQueryWrapper2.eq("eid",enterprise.getEnterpriseId()).eq("situation","死淘").between("changeTime",firstDay,lastDay);
                List<Production> productions2=productionService.list(productionQueryWrapper2);
                int maleHarmlessSum=0,femaleHarmlessSum=0,breedFemaleHarmlessSum=0,lactationHarmlessSum=0,conservationHarmlessSum=0,growHarmlessSum=0;
                for(Production production:productions2){
                    maleHarmlessSum=maleHarmlessSum+production.getMale();
                    femaleHarmlessSum=femaleHarmlessSum+production.getFemale();
                    breedFemaleHarmlessSum=breedFemaleHarmlessSum+production.getBreedFemale();
                    lactationHarmlessSum=lactationHarmlessSum+production.getLactation();
                    conservationHarmlessSum=conservationHarmlessSum+production.getConservation();
                    growHarmlessSum=growHarmlessSum+production.getGrow();
                }
                monthReportRecord.setMaleHarmless(maleHarmlessSum);         //设置种公畜无害化处理数
                monthReportRecord.setFemaleHarmless(femaleHarmlessSum);     //设置后备母畜无害化处理数
                monthReportRecord.setBreedFemaleHarmless(breedFemaleHarmlessSum);       //设置能繁母畜无害化处理数
                monthReportRecord.setLactationHarmless(lactationHarmlessSum);           //设置哺乳牲畜无害化处理数
                monthReportRecord.setConservationHarmless(conservationHarmlessSum);     //设置保育牲畜无害化处理数
                monthReportRecord.setGrowHarmless(growHarmlessSum);         //设置育成牲畜无害化处理数
                monthReportRecord.setHarmlessSum(maleHarmlessSum+femaleHarmlessSum+breedFemaleHarmlessSum+lactationHarmlessSum+conservationHarmlessSum+growHarmlessSum);        //设置无害化处理总数
                monthReportRecordService.save(monthReportRecord);
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    /**
     * 传入一个日期获得上个月第一天至最后一天的日期
     */
    List<String> getDay(Date date) {
        List<String> strings = new ArrayList<>();
        //获取当前月份
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String firstday, lastday;
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        //当前月份减1
        c.add(Calendar.MONTH, -1);

        // 获取上个月的第一天
        c.set(Calendar.DAY_OF_MONTH, 1);
        firstday = df.format(c.getTime());
        strings.add(firstday);
        // 获取上个月的最后一天
        c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_MONTH, 0);
        lastday = df.format(c.getTime());
        strings.add(lastday);
        System.out.println("上个月第一天：" + firstday + ";上个月最后一天：" + lastday);
        return strings;
    }
}

